package com.fee1in;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

class XMLMapperBuilder {
   private Configuration configuration;
   private String resource;

   public XMLMapperBuilder(Configuration configuration, String resource) {
      this.configuration = configuration;
      this.resource = resource;
   }

   public void parse(){
      try (InputStream is = getClass().getClassLoader().getResourceAsStream(resource)){

         SAXReader saxReader = new SAXReader();
         Document document = saxReader.read(is);
         configurationElement(document.getRootElement());

      } catch (Exception e) {
         e.printStackTrace();
      }



   }

   private void configurationElement(Element mapper) {
      String namespace = mapper.attributeValue("namespace");
      buildStatement(namespace,mapper.selectNodes("//select"));

   }


   private void buildStatement(String namespace,List<Element> statements){
      for (Element element:statements){
         String id = element.attributeValue("id");
         String resultType = element.attributeValue("resultType");
         String sql = element.getText();
         MappedStatement mappedStatement = new MappedStatement();
         mappedStatement.setId(namespace+"."+id);
         mappedStatement.setResultType(resultType);
         mappedStatement.setSql(sql);
         configuration.addMappedStatement(mappedStatement);
      }


   }
}
